package com.study.samsung.Dao;

import com.study.samsung.Entity.Collect;
import com.study.samsung.Entity.User;
import com.study.samsung.Utils.Pager;
import com.study.samsung.Utils.RowMapper;
import com.study.samsung.Utils.SQLHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CollectDAO {
    private SQLHelper helper = new SQLHelper();

    public List<Collect>selectAllCol(Integer uid){
        String sql = "SELECT * FROM commodity a LEFT JOIN collect c ON a.sid = c.sid WHERE uid=?";
        return helper.query(sql,new CollectRowMpper(),uid);
    }

    public List<Collect> selectAllImg(Integer uid,Integer pageno){
        String sql = "SELECT * FROM commodity a LEFT JOIN collect c ON a.sid = c.sid WHERE uid=? LIMIT ?,3";
        return helper.query(sql,new CollectRowMpper(),uid,(pageno-1)*3);
    }

//    分页：
public Pager selectAllColfy(Integer uid, Integer pageno, Integer pagesize){
    ArrayList<Object> params = new ArrayList<>();
    String sql1 = "SELECT count(*) FROM commodity a LEFT JOIN collect c ON a.sid = c.sid WHERE uid=?";
    Integer total = helper.one(sql1, rs->{
        return rs.getInt(1);
    },uid);

    params.add(uid);
    params.add((pageno-1)*pagesize);
    params.add(pagesize);
    String sql2 = "select * from commodity a left join collect c on a.sid = c.sid where uid=? limit ?,?";
    List<Collect> findMycollec = helper.query(sql2, new CollectRowMpper(),params.toArray());
    Pager pager = new Pager(pageno,pagesize);
    pager.setTotal(total);
    pager.setData(findMycollec);
    return pager;
}

    public Collect selectOne(Integer uid,Integer sid){
        String sql = "SELECT * FROM commodity a LEFT JOIN collect c ON a.sid = c.sid WHERE c.uid=? AND c.sid=?";
        return helper.one(sql,new CollectRowMpper(),uid,sid);
    }

    class CollectRowMapperParent implements RowMapper<Collect>{

        @Override
        public Collect map(ResultSet rs) throws SQLException {
            return new Collect(rs.getInt("cid"),
                               rs.getDate("ctime"),
                                rs.getInt("sid")
                    );
        }
    }
    class CollectRowMpper extends CollectRowMapperParent{
        @Override
        public Collect map(ResultSet rs) throws SQLException {
            Collect collect = super.map(rs);
            collect.setLid(rs.getInt("lid"));
            collect.setSname(rs.getString("sname"));
            collect.setUrl(rs.getString("url"));
            collect.setSprice(rs.getBigDecimal("sprice"));
            return collect;
        }
    }
}
